import com.changshengwei.Apple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 07509-Chang Shengwei
 * @version Id: FilterApple.java, v 0.1 2021/6/3 10:36 Chang Shengwei Exp $
 * @description
 */
public class FilterApple {

    /**
     * 策略模式
     */

    private interface AppleFilter {

        /**
         * filter
         * @param apple
         * @return
         */
        boolean filter(Apple apple);

    }

    public static class GreenAndWeight150Filter implements AppleFilter{

        @Override
        public boolean filter(Apple apple) {
            return ("green".equals(apple.getColor()) && apple.getWeight() >= 150);
        }
    }

    /**
     * 原始写法
     * @param apples
     * @param appleFilter
     * @return
     */
    public static List<Apple> findApple(List<Apple> apples, AppleFilter appleFilter){
        List<Apple> list = new ArrayList<>();
        for (Apple apple: apples){
            if (appleFilter.filter(apple)){
                list.add(apple);
            }
        }
        return list;
    }


    public static void main(String[] args) throws InterruptedException {

        List<Apple> apples = Arrays.asList(new Apple("green", 120), new Apple("green", 150),
                new Apple("red", 160));

        List<Apple> result = findApple(apples, new GreenAndWeight150Filter());
        // System.out.println(result);


        // 匿名内部类
        List<Apple> redAppleResult = findApple(apples, new AppleFilter() {
            @Override
            public boolean filter(Apple apple) {
                return "red".equals(apple.getColor());
            }
        });

        // System.out.println(redAppleResult);


        List<Apple> greenAppleResultWithLambda1 = findApple(apples, (Apple apple) -> {
            return "green".equals(apple.getColor());
        });

        // lambda，参数可以推导是apple类型，所以不用加Apple，因为只有一个参数，可以不用加括号，也不需要声明return,可以推到，如果加了
        // 花括号，就得用return
        List<Apple> greenAppleResultWithLambda2 = findApple(apples, apple ->
            "green".equals(apple.getColor())
        );

        // System.out.println(greenAppleResultWithLambda2);
        // System.out.println(greenAppleResultWithLambda1);


        // 匿名内部类创建、启动线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
        }).start();

        // lambda创建、启动线程
        new Thread(() -> System.out.println(Thread.currentThread().getName())).start();

        Thread.currentThread().join();
    }
}
